<?php
namespace App\Services;

use App\Models\Tour;
use App\Models\TourCategory;
use App\Models\TourOrderEvaluation;
use App\Models\TourSchedule;
use App\Models\TourSettings;
use App\Models\TourStatistics;
use Illuminate\Support\Facades\DB;

/**
 *
 * 旅游线路服务层
 *
 * @author maqu
 *
 */
class TourService extends BaseService {

    /**
     * 更新统计数据
     * @auth shengl 2017年3月25日11:00:05
     * @param $tour_id
     * @param string $column
     */
    public function update_statistics($tour_id,$column ='views'){
        TourStatistics::where('tour_id',$tour_id)->increment($column);
    }

    /**
     * 获取指定ID的线路详情
     * @auth shengl 2017年3月25日10:59:39
     * @param $tour_id
     * @param int $user_id
     * @param bool|false $collect_flg
     * @return array
     */
    public function getTourDetail($tour_id,$user_id=0,$collect_flg=false){

        //获取数据
        $tour =Tour::where('if_show',YES)
//            ->where('hidden',NO)
            ->with(["tourExtra"=>function($query){
                $query->select('tour_id','route_feature','route_schedule','cost_payed','cost_yourself','notice','hints','travel_days');
            },"tourImage","tourSchedule"=>function($query) {
                $query->where('open_date','>',gmtime())->orderBy('open_date','asc')->skip(0)->take(4);
            },"tourStatistics"])
            ->select('tour_id','hidden','store_id','tour_name','brief','closed','tags','allow_singlebuy','allow_groupbuy','default_image','adult_child_joinflg','price_a','stock_defined')
            ->find($tour_id);

        //商品存在性判断
        if (!$tour) {
            return $this->failure('未找到对应的路线');
        }
        $tour->min_price = $tour->price_a;
        $tour->default_image = complete_url( $tour->default_image);

        //出行前多少天可以购买
        $stopsale_days = TourSettings::where('tour_id',$tour_id)->value('stopsale_days');

        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'), $tour->tour_name,$tour->tourExtra->route_feature);
        $tour->tourExtra->route_feature = $html;
        unset($html);
        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'), $tour->tour_name,$tour->tourExtra->route_schedule);
        $tour->tourExtra->route_schedule = $html;
        unset($html);
        foreach($tour->tourSchedule as $item){
            $rest_time = strtotime(local_date_ymd($item->open_date))-strtotime(local_date_ymd(gmtime()));
            $rest_date = $rest_time/86400;
            $item->can_choose = $rest_date > $stopsale_days ? 1:0;
            $item->singlebuy_config = json_decode($item->singlebuy_config);
            $item->groupbuy_config = json_decode($item->groupbuy_config);
            $item->open_date_fmt = local_date('m-d',$item->open_date);
        }

        //商品相册
        foreach ($tour->tourImage as $key=>$item){
            if(!empty($item->image_url)){
                $item->image_url = complete_url($item->image_url);
            }
            if(!empty($item->thumbnail)){
                $item->thumbnail = complete_url($item->thumbnail);
            }
        }

        if($tour->tourStatistics){
            $count_evaluation = DB::table('tour_order_evaluation')->where('tour_id',$tour_id)->avg('evaluation_score');
            $tour->tourStatistics->gpa = sprintf("%.1f",$count_evaluation);
        }

        //收藏状态
        if($collect_flg && $user_id){
            $count= DB::table('collect')
                ->where('user_id',$user_id)
                ->where('type','tour')
                ->where('item_id',$tour_id)->count();
            $tour->collect_status=$count?1:0;
        }else{
            $tour->collect_status=0;
        }
//        {"services":["genuine","7day","excellege"]}["genuine","excellege"]

        return $this->success($tour);

    }
//
//    /**计算最低价格
//     * @auth shengl 2017年3月25日11:00:05
//     * @param $tour_id
//     * @param $adult_child_joinflg
//     * @return int|mixed
//     */
//    public static function getTourMinPrice($tour_id,$adult_child_joinflg){
//        $tourSchedule = TourSchedule::where('tour_id',$tour_id)->where('open_date','>',gmtime())->get();
//        $min_price = 0;
//        foreach($tourSchedule as $item){
//            $singlebuy_config = json_decode($item->singlebuy_config);
//            switch($adult_child_joinflg){
//                case TOUR_JOIN_ADULT_ONLY:
//                    if($min_price > 0){
//                        $min_price = min([$min_price,$singlebuy_config->price_a]);
//                    }else{
//                        $min_price = $singlebuy_config->price_a;
//                    }
//                    break;
//                case TOUR_JOIN_CHILD_ONLY:
//                    if($min_price > 0){
//                        $min_price = min([$min_price,$singlebuy_config->price_c]);
//                    }else{
//                        $min_price = $singlebuy_config->price_c;
//                    }
//                    break;
//                default:
//                    if($min_price > 0){
//                        $min_price = min([$min_price,$singlebuy_config->price_a,$singlebuy_config->price_c]);
//                    }else{
//                        $min_price = min([$singlebuy_config->price_a,$singlebuy_config->price_c]);
//                    }
//            }
//
//            $groupbuy_config = json_decode($item->groupbuy_config);
//            foreach($groupbuy_config->prices as $group_price){
//                $min_price = min([$min_price,$group_price->price]);
//            }
//        }
//
//        return $min_price;
//    }

    /**
     * 按月获取旅游线路的日程安排
     * @auth shengl 2017年3月25日15:59:18
     * @param $tour_id
     * @param string $buy_type
     * @param $month
     * @return array
     */
    public function getScheduleByMonth($tour_id,$buy_type=TOUR_ORDER_EXTENSION_NORMAL,$month){
        $monthFirstTime = strtotime($month);

        $monthFirstTimeStr = date("Y-m-01", $monthFirstTime);
        $monthLastTime = strtotime(date('Y-m-d 23:59:59',   strtotime("$monthFirstTimeStr +1 month -1 day")));

        $tourSchedule = TourSchedule::where('tour_id',$tour_id)->whereBetween('open_date', [$monthFirstTime, $monthLastTime])->get();

        if(!$tourSchedule){
            return $this->failure('当月无日程');
        }

        //出行前多少天可以购买
        $stopsale_days = TourSettings::where('tour_id',$tour_id)->value('stopsale_days');

        foreach($tourSchedule as $k => $item){
            $rest_time = strtotime(local_date('Y-m-d',$item->open_date))-strtotime(local_date('Y-m-d',gmtime()));
            $rest_date = $rest_time/86400;

            //剩余天数不足，不可购买
            $item->can_choose = $rest_date > $stopsale_days ? 1:0;
            $item->singlebuy_config = json_decode($item->singlebuy_config);
            $item->groupbuy_config = json_decode($item->groupbuy_config);
            $item->open_date_fmt = local_date('Y-m-d',$item->open_date);
            if($buy_type == TOUR_ORDER_EXTENSION_NORMAL && $item->stock == 0){
                $item->can_choose = 0;
            }

            if($buy_type == TOUR_ORDER_EXTENSION_GROUPBUY){
                //库存人数不足的团购类型自动删除
                foreach($item->groupbuy_config->prices as $conf){
                    if(($item->groupbuy_config->limit_a * $conf->peoples )>$item->stock){
                        unset($conf);
                    }
                }
                //如果一个团购类型都没有了，则不可购买
                if(empty($item->groupbuy_config->prices)){
                    $item->can_choose = 0;
                }
            }

        }
        return $this->success($tourSchedule);
    }
    
    public function getTourCategories(){

        $datas = TourCategory::where('if_show',1)
            ->where('store_id',0)
            ->orderBy('sort_order','asc')
            ->get();

        if($datas){
            foreach($datas as $d){
                $d->pic_url = complete_url($d->pic_url);
                $d->adv_url = complete_url($d->adv_url);
            }
        }

        return $datas;

    }

    /**
     * 根据分类获取旅游路线
     *
     * @param $cate_id
     * @param $province
     * @param $lat
     * @param $lon
     * @param $level
     * @param $city
     * @param $country
     * @param $sort_type
     * @param $sort
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getToursByCate($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){

    //参数
        //【排序】
        //  sort_type 排序方式 price or sales or distance
        //  sort    升降序 asc or desc
        //【位置】
        // country 0-all or 选择的县的regionid
        //【翻页】
        //firsstrow
        //pagesize

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}

        $data = [
            'category'=>[],
            'countries'=>[],
            'tours'=>[]
        ];

        $cate = TourCategory::find($cate_id);
        if(!$cate){
            return $this->failure('线路主题不存在');
        }

        $data['category']=[
            'cate_id'=>$cate->cate_id,
            'cate_name'=>$cate->cate_name,
            'pic_url'=>complete_url($cate->pic_url),
            'adv_url'=>complete_url($cate->adv_url)
        ];

        //基础
        $query =DB::table('tour')
            ->where('cate_id',$cate_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }

        if($city){
            $query->where('city',$city);
        }
//        if($country && $country != '全部'){
//            $query->where('country',$country);
//        }
        if($country == '全部'){
            $country = 0;
        }


        //统计线路数量
        $groupdata = $query->groupBy('country')
            ->select(DB::raw('country,count(*) as num'))
            ->get();

        $total =0;
        //$data['countries'][]=['item_id'=>0,'item_name'=>'全部','count'=>$total];
        if($groupdata){
            foreach($groupdata as $item){
                $total+=$item->num;
            }
            $data['countries'][]=['item_id'=>0,'item_name'=>'全部','count'=>$total];
            foreach($groupdata as $item){
                $data['countries'][]=['item_id'=>$item->country,'item_name'=>$item->country,'count'=>$item->num];
            }
        }

        unset($total,$groupdata,$query);

        switch($sort_type){
            case 'price':

                $tourdata = $this->getToursByCate_orderByPrice($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){
                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['tours']=$tourdata;
                }

                break;
            case 'sales':

                $tourdata = $this->getToursByCate_orderBySales($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){

                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['tours']=$tourdata;
                }

                break;
            case 'views':

                $tourdata = $this->getToursByCate_orderByViews($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){

                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['tours']=$tourdata;
                }

                break;
            case 'distance':

                $tourdata = $this->getToursByCate_orderByDistance($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize);

                if($tourdata){

                    foreach($tourdata as  $value){
                        $value->default_image = complete_url( $value->default_image);
                        $value->default_image2 = complete_url( $value->default_image2);
                    }
                    $data['tours']=$tourdata;
                }
                break;
            default:
                return $this->failure('未实现');

        }

        return $this->success($data);

    }
    private function getToursByCate_orderByPrice($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){

        $query =DB::table('tour')
            ->where('cate_id',$cate_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        tour_sn,tour_name,short_name,tags,brief,default_image,default_image2,price_a,province,city,country"),'tour.tour_id');

        $tourdata = $query
            ->orderBy('price_a',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;

    }

    private function getToursByCate_orderBySales($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){
        $query =DB::table('tour')
            ->leftJoin('tour_statistics','tour.tour_id','=','tour_statistics.tour_id')
            ->where('cate_id',$cate_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        tour_sn,tour_name,short_name,brief,tags,default_image,default_image2,price_a,province,city,country"),'tour.tour_id');

        $tourdata = $query
            ->orderBy('tour_statistics.sales',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;
    }

    private function getToursByCate_orderByViews($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){
        $query =DB::table('tour')
            ->leftJoin('tour_statistics','tour.tour_id','=','tour_statistics.tour_id')
            ->where('cate_id',$cate_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        tour_sn,tour_name,short_name,brief,tags,default_image,default_image2,price_a,province,city,country"),'tour.tour_id');

        $tourdata = $query
            ->orderBy('tour_statistics.views',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;
    }

    private function getToursByCate_orderByDistance($cate_id,$lat,$lon,$province,$city,$country,$sort_type,$sort,$firstrow,$pagesize){

        $query =DB::table('tour')
            ->where('cate_id',$cate_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        if($province){
            $query->where('province',$province);
        }
        if($city){
            $query->where('city',$city);
        }
        if($country){
            $query->where('country',$country);
        }

        $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        tour_sn,tour_name,short_name,tags,brief,default_image,default_image2,price_a,province,city,country"),'tour.tour_id');

        $tourdata = $query
            ->orderBy('distance',$sort)
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        return $tourdata;

    }

    /**
     * 获取线路的评价列表
     * @param $tour_id
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getComments($tour_id,$firstrow,$pagesize){

        $tour = Tour::find($tour_id);

        if(!$tour){
            return $this->failure('该线路不存在');
        }

        $comments = TourOrderEvaluation::where('tour_id',$tour_id)
            ->where('evaluation_if_show',1)
            ->orderBy('evaluation_time', 'desc')
            ->skip($firstrow)
            ->take($pagesize)
            ->get();

        $comments = $comments->toArray();
        if(count($comments)>0){
            foreach($comments as $k=>$item){
                $comments[$k]['evaluation_time'] = local_date_ymd($item['evaluation_time']);
                $comments[$k]['buyer_avatar'] = complete_url($item['buyer_avatar']);
                $images = json_decode($item['pictures'],true);

                if (is_array($images)&&count($images)>0)
                {
                    foreach($images as $image){
                        $comments[$k]["images"][] = complete_url($image);
                    }
                }
                else
                {
                    $comments[$k]['images'] = '';
                }
                unset($comments[$k]['pictures']);
            }
        }
        return $this->success($comments);

    }

    /**
     * 获取指定店铺的线路列表
     *
     * @param $store_id
     * @param $lat
     * @param $lon
     * @param $firstrow
     * @param $pagesize
     * @return null
     */
    public function getVillagerToursByStoreId($store_id,$lat,$lon,$firstrow,$pagesize){

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        $query =DB::table('tour')
            ->where('store_id',$store_id)
            ->where('if_show',1)
            ->where('closed',0)
            ->where('hidden',0);

        $tourdata=null;

        if($lat==999 && $lon ==999){
            $query->select(DB::raw("country as distance,tour_sn,tour_name,short_name,brief,default_image,default_image2,price_a,province,city,country"),'tour.tour_id');

            $tourdata = $query
                ->orderBy('add_time','desc')
                ->skip($firstrow)
                ->take($pagesize)
                ->get();

        } else {
            $query->select(DB::raw("round(6378.138*2*asin(sqrt(pow(sin(($lat*pi()/180-latitude*pi()/180)/2),2)+cos($lat*pi()/180)*cos(latitude*pi()/180)* pow(sin( ($lon*pi()/180-longitude*pi()/180)/2),2)))*1000) as distance,
        tour_sn,tour_name, short_name,brief,default_image,default_image2,price_a,province,city,country"),'tour.tour_id');

            $tourdata = $query
                ->orderBy('add_time','desc')
                ->orderBy('distance','asc')
                ->skip($firstrow)
                ->take($pagesize)
                ->get();
        }

        if($tourdata){
            foreach($tourdata as $d){
                $d->default_image = complete_url($d->default_image);
                $d->default_image2 = complete_url($d->default_image2);
            }
        }
       // var_dump($tourdata);die();
        return $this->success($tourdata);
    }

}